package com.chinacoal.microservice.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.CcmsSmartleasingBuildingMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingHouseTypeMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingRoomMapper;
import com.chinacoal.microservice.pojo.CcmsSmartleasingBuilding;
import com.chinacoal.microservice.pojo.CcmsSmartleasingRoom;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.BuildingInformationService;
import com.chinacoal.microservice.util.CodeMsg;
import com.chinacoal.microservice.util.QueryCriteria;
import com.chinacoal.microservice.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 房源管理-楼宇管理实现类
 * @date 2020-11-06 18：49
 */
@Service
@Slf4j
public class BuildingInformationServiceImpl implements BuildingInformationService {

    @Autowired
    private CcmsSmartleasingBuildingMapper smartleasingBuildingMapper;

    @Autowired
    private CcmsSmartleasingRoomMapper roomMapper;

    @Autowired
    private CcmsSmartleasingHouseTypeMapper houseTypeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @author zhuliang
     * @Description: 根据楼宇名模糊查询(带分页)
     * @date 2020-11-09 11：18
     */
    @Override
    public Result<List<CcmsSmartleasingBuilding>> getLikeBuildingName(QueryCriteria queryCriteria, String token) {
        //得到登录人id,并做兼容性处理
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingBuilding> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始条件查询
        List<CcmsSmartleasingBuilding> buildings = smartleasingBuildingMapper.getAllByCondition(toPage,
                                                                                                queryCriteria.getInputString(),
                                                                                                queryCriteria.getProvinceId(),
                                                                                                queryCriteria.getCityId(),
                                                                                                queryCriteria.getAreaId(),
                                                                                                currency.getProperty(),
                                                                                                currency.getManagementOffice());

        return Result.success(buildings, toPage.getTotal());
    }

    /**
     * @author zhuliang
     * @Description: 查询所有的楼宇信息(带分页)
     * @date 2020-11-09 13：50
     */
    @Override
    public Result<List<CcmsSmartleasingBuilding>> getAllHouses(QueryCriteria queryCriteria, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingBuilding> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询
        List<CcmsSmartleasingBuilding> buildings = smartleasingBuildingMapper.getAllByPage(toPage,
                                                                                            currency.getProperty(),
                                                                                            currency.getManagementOffice());

        return Result.success(buildings,toPage.getTotal());
    }


    /**
     * @author zhuliang
     * @Description: 根据楼宇id查询对应的楼宇信息
     * @date 2020-11-09 13：57
     */
    @Override
    public Result<CcmsSmartleasingBuilding> getHousesById(String pkBuildingId, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //通过楼宇id，得到对应的楼宇信息
        CcmsSmartleasingBuilding building = smartleasingBuildingMapper.getBuildingById(pkBuildingId,
                                                                                        currency.getProperty(),
                                                                                        currency.getManagementOffice());

        //兼容性判断
        if (null == building) {
            log.error(CodeMsg.NOT_FOUND.toString() + "-->此楼宇信息无权限访问，或数据丢失-->" + pkBuildingId);
            return Result.error(CodeMsg.NOT_FOUND);
        }

        //拆分地址
        if (StringUtils.isNotBlank(building.getPropertyOwnershipCertificate())) {
            String[] split = building.getPropertyOwnershipCertificate().split(",");
            building.setPropertyOwnershipCertificateList(split);
        }

        return Result.success(building);
    }

    /**
     * @author zhuliang
     * @Description: 添加楼宇信息
     * @date 2020-11-09 14：20
     */
    @Override
    public Result addHouses(CcmsSmartleasingBuilding building, String token){
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //添加默认的参数
        building.setPkBuildingId(UUID.randomUUID() + "");
        building.setCreationDate(new Date());
        building.setLastUpdateDate(new Date());
        building.setCreatedBy(currency.getLoginId());
        building.setLastUpdatedBy(currency.getLoginId());

        //添加楼宇信息
        smartleasingBuildingMapper.insert(building);

        return Result.success();
    }

    /**
     * @author zhuliang
     * @Description: 修改楼宇信息
     * @date 2020-11-09 14：38
     */
    @Override
    public Result updateHouses(CcmsSmartleasingBuilding building, String token){
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //完善修改的楼宇信息
        building.setLastUpdateDate(new Date());
        building.setLastUpdatedBy(currency.getLoginId());

        //根据楼宇信息的id进行修改
        smartleasingBuildingMapper.updateById(building);

        return Result.success();
    }

    /**
     * @author zhuliang
     * @Description: 根据楼宇id删除对应的楼宇信息
     * @date 2020-11-09 14：52
     */
    @Override
    public Result deleteHouses(String token, String deleteId) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //判断是否和房间和户型还有关联
        String roomCount = roomMapper.getCountByBuildingId(deleteId);
        String houseTypeCount = houseTypeMapper.getCountByBuildingId(deleteId);

        if (StringUtils.isNotBlank(roomCount) || StringUtils.isNotBlank(houseTypeCount)) {
            log.error(CodeMsg.DATA_HAS_BEEN_USED.toString() + "-->楼宇已经被使用，不能删除");
            return Result.error(CodeMsg.DATA_HAS_BEEN_USED);
        }

        //根据楼宇id进行修改
        smartleasingBuildingMapper.updateToDeleteById("1",
                                                        new Date(),
                                                        deleteId,
                                                        currency.getLoginId(),
                                                        currency.getProperty(),
                                                        currency.getManagementOffice());
        
        return Result.success();
    }

    /**
     * @Description: 查询所有的楼宇信息
     * @author zhuliang
     * @date 2020/11/12 13:50
     */
    @Override
    public Result<List<CcmsSmartleasingBuilding>> getAll(String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //查询所有的楼宇信息
        List<CcmsSmartleasingBuilding> buildings = smartleasingBuildingMapper.getAllName(currency.getProperty(),
                                                                                         currency.getManagementOffice());

        //返回对应的信息
        return Result.success(buildings);
    }

    /**
     * @Description: 根据楼宇id查询所有的省市区街道，房间
     * @author zhuliang
     * @date 2020/12/2 18:32
     */
    @Override
    public Result<CcmsSmartleasingBuilding> getAllByBuildingId(String pkBuildingIds, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //根据楼宇id查询
        CcmsSmartleasingBuilding buildings = smartleasingBuildingMapper.getAllByBuildingId(pkBuildingIds,
                                                                                            currency.getProperty(),
                                                                                            currency.getManagementOffice());

        //查询对应的房间信息,并放入返回值中
        List<CcmsSmartleasingRoom> rooms = roomMapper.getAllByBuildingId(buildings.getPkBuildingId());
        buildings.setRoomList(rooms);

        return Result.success(buildings);
    }

    /**
     * @Description: 根据区域编号id查询楼宇信息
     * @author zhuliang
     * @date 2020/12/2 18:46
     */
    @Override
    public Result<List<CcmsSmartleasingBuilding>> getAllByAreaNumberId(String areaNumberId, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //根据区域编号id查询
        List<CcmsSmartleasingBuilding> buildings = smartleasingBuildingMapper.getAllByAreaNumberId(areaNumberId,
                                                                                                    currency.getProperty(),
                                                                                                    currency.getManagementOffice());

        return Result.success(buildings);
    }
}
